/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.service.plugin;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.client.InfoReleaseCoreCleint;
import com.apache.client.LogClient;
import com.apache.info.entity.PubMetadata;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.AnntationBean;
import com.apache.portal.common.enums.InfoMethodEnum;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.DateUtils;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * description:  消息通知插件
 *
 * @author Hou Dayu 创建时间：2016-8-29
 */
@AnntationBean(name = "info")
public class InfoSystemPluginImpl implements PortalPlugin {

    public Object doInvoke(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        Object result = null;
        String doCode = params.get("doCode");
        if (StrUtil.isNull(doCode)) {
            doCode = request.getParameter("doCode");
        }
        switch (InfoMethodEnum.getName(doCode)) {
        case Add:
            result = saveInfo(request, params);
            break;
        case Edit:
            result = editInfo(request, params);
            break;
        case Del:
            result = delInfo(request, params);
            break;
        case Subsave:
            result = saveSubInfo(request, params);
            break;
        case Subeidt:
            result = editsubInfo(request, params);
            break;
        case Subdel:
            result = delSubInfo(request, params);
            break;
        case createDatabase:
            params.put("method", "createDatabase");
            result =  getInfoResultInfo("sortInfoAction", params);
            break;
        case saveSortInfo:
            params.put("method", "save");
            result = getInfoResultInfo("sortInfoAction", params);
            break;
        case delSortInfo:
            params.put("method", "del");
            result = getInfoResultInfo("sortInfoAction", params);
            break;
        case listSortInfo:
            params.put("method", "list");
            result = getInfoResultInfo("sortInfoAction", params);
            break;
        case publish:
            params.put("method", "publish");
            result = getInfoResultInfo("sortInfoAction", params);
            break;
        case sotp:
            params.put("method", "stop");
            result = getInfoResultInfo("sortInfoAction", params);
            break;
        case saveMetadata:
            params.put("method", "save");
            result = getInfoResultInfo("metadataAction", params);
            break;
        case delMetadata:
            params.put("method", "del");
            result = getInfoResultInfo("metadataAction", params);
            break;
        case listMetadata:
            params.put("method", "list");
            result = getInfoResultInfo("metadataAction", params);
            break;
        case initCache:
            params.put("method", "initCache");
            result = getInfoResultInfo("metadataAction", params);
            break;
        default:
            return rpcManager(request, params);
        }
        return result;
    }

    private ResultEntity getInfoResultInfo(String methodKey, Map params) {

        return LoadRpcService.service().doServiceClient("infoService", methodKey, params,
                PortalPubFactory.getInstance().getRpcInfo("info"));
    }

    private ResultEntity rpcManager(HttpServletRequest request, Map<String, String> params) {
        String doCode = params.get("doCode");
        String methodKey = "protocolAction";
        if ("saveProtocol".equals(doCode)) {
            params.put("method", "save");
        } else if ("loadCache".equals(doCode)) {
            params.put("method", "loadCache");
        } else if ("listProtocol".equals(doCode)) {
            params.put("method", "list");
        } else if ("infoProtocol".equals(doCode)) {
            params.put("method", "info");
        } ///以下为数据源接口
        else if ("saveDatasource".equals(doCode)) {
            params.put("method", "save");
            methodKey = "datasourceAction";
        } else if ("loadDatasource".equals(doCode)) {
            params.put("method", "loadCache");
            methodKey = "datasourceAction";
        } else if ("listDatasource".equals(doCode)) {
            params.put("method", "list");
            methodKey = "datasourceAction";
        } else if ("infoDatasource".equals(doCode)) {
            params.put("method", "info");
            methodKey = "datasourceAction";
        }///以下是定时任务接口
        else if("saveTaskTimer".equals(doCode)){
            params.put("method", "save");
            methodKey = "taskTimerAction";
        }else if("loadTaskTimer".equals(doCode)){
            params.put("method", "loadCache");
            methodKey = "taskTimerAction";
        }else if("listTaskTimer".equals(doCode)){
            params.put("method", "list");
            methodKey = "taskTimerAction";
        }else if("infoTaskTimer".equals(doCode)){
            params.put("method", "info");
            methodKey = "taskTimerAction";
        }else if("delTaskTimer".equals(doCode)){
            params.put("method", "del");
            methodKey = "taskTimerAction";
        }

        return getRpcResultInfo(methodKey, params);
    }

    private ResultEntity getRpcResultInfo(String methodKey, Map params) {

        return LoadRpcService.service().doServiceClient("rpcService", methodKey, params,
                PortalPubFactory.getInstance().getRpcInfo("rpc"));
    }

    /**
     * description:  主子表联插
     */
    private ResultMsg saveSubInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = null;
        String tabName = params.get("tabName");
        String sortCodes[] = tabName.split(",");
        List<PubMetadata> list = new ArrayList<PubMetadata>();
        for (int i = 0; i < sortCodes.length; i++) {
            List<PubMetadata> pms = InfoReleaseCoreCleint.getInstance()
                    .getMetadatas(sortCodes[i], params.get("sysName"));
            if (null != pms)
                list.addAll(pms);
        }
        if (null == list)
            return null;
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        params.put("userOrg", loginUser.getOrgEname());
        params.put("createUser", loginUser.getUserEname());
        params.put("createTime", DateUtils.getNow());
        params.put("infoId", UUID.randomUUID().toString().replaceAll("-", ""));
        params.put("subId", params.get("infoId"));
        params.put("mainSortCode", sortCodes[0]);
        params.put("subSortCode", sortCodes[1]);
        params.put("subSortId", sortCodes[1]);
        for (PubMetadata pm : list) {
            if ("6".equals(pm.getDataType()) && "2".equals(pm.getDataRestrict())) {//处理日期类型
                if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
                    params.put(pm.getDataAttr(),
                            DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }
            } else if ("2".equals(pm.getDataRestrict())) {
                if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
                    json = new ResultMsg("F", "表单的必填项不可为空");
                    return json;
                }
            }
        }
        json = InfoReleaseCoreCleint.getInstance().saveMasterSlaveInfo(params);
        if (null != json && "T".equals(json.getFlag())) {
            this.addLogInfo("save", "com.apache.pubInfo." + sortCodes[1], request, params);
        }
        return json;
    }

    /**
     * description:  主子表联改
     */
    private ResultMsg editsubInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = null;
        String tabName = params.get("tabName");
        String sortCodes[] = tabName.split(",");
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        params.put("mainSortCode", sortCodes[0]);
        params.put("subSortCode", sortCodes[1]);
        params.put("modifyUser", loginUser.getUserEname());
        params.put("modifyTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        if (StrUtil.isNull(params.get("infoId"))) {//处理主键
            json = new ResultMsg("F", "非空参数不可为空");
            return json;
        }
        params.put("subId", params.get("infoId"));
        json = InfoReleaseCoreCleint.getInstance().updateMasterSlaveInfo(params);
        if (null != json && "T".equals(json.getFlag())) {
            this.addLogInfo("edit", "com.apache.pubInfo." + sortCodes[1], request, params);
        }
        return json;
    }

    /**
     * description:  主子表联删
     */
    private ResultMsg delSubInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = null;
        String tabName = params.get("tabName");
        String sortCodes[] = tabName.split(",");
        params.put("mainSortCode", sortCodes[0]);
        params.put("subSortCode", sortCodes[1]);
        if (StrUtil.isNull(params.get("infoId"))) {//处理主键
            json = new ResultMsg("F", "非空参数不可为空");
            return json;
        }
        params.put("subId", params.get("infoId"));
        json = InfoReleaseCoreCleint.getInstance().deleteInfo(params);
        if (null != json && "T".equals(json.getFlag())) {
            this.addLogInfo("del", "com.apache.pubInfo." + sortCodes[1], request, params);
        }
        return json;
    }

    /**
     * description:  单表保存
     */
    private ResultMsg saveInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = null;
        List<PubMetadata> list = InfoReleaseCoreCleint.getInstance()
                .getMetadatas(params.get("sortCode"), params.get("sysName"));
        if (null == list) {
            json = new ResultMsg("F", params.get("sortCode") + "表单未找到相关属性");
            return json;
        }
        if (StrUtil.isNull(params.get("createUser"))) {
            LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
            params.put("createUser", loginUser.getUserEname());
        }
        params.put("createTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        params.put("isTopTime", params.get("createTime"));//初始化默认登录创建时间
        for (PubMetadata pm : list) {
            if ("1".equals(pm.getDataRestrict())) {//处理主键
                params.put(pm.getDataAttr(), UUID.randomUUID().toString().replaceAll("-", ""));
            } else if ("6".equals(pm.getDataType()) && "2".equals(pm.getDataRestrict())) {//处理日期类型
                if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
                    params.put(pm.getDataAttr(),
                            DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                }
            } else if ("2".equals(pm.getDataRestrict())) {
                if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
                    json = new ResultMsg("F", "表单的必填项不可为空");
                    return json;
                }
            }
        }
        json = InfoReleaseCoreCleint.getInstance().saveInfo(params);
        if (null != json && "T".equals(json.getFlag())) {
            this.addLogInfo("save", "com.apache.pubInfo." + params.get("sortCode"), request,
                    params);
        }
        return json;
    }

    /**
     * description:  单表修改
     */
    private ResultMsg editInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = null;
        PubMetadata pm = InfoReleaseCoreCleint.getInstance()
                .getMetadataPrimarykey(params.get("sortCode"), params.get("sysName"));
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        params.put("modifyUser", loginUser.getUserEname());
        params.put("modifyTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        if (null != pm) {
            if ("1".equals(pm.getDataRestrict())) {//处理主键
                if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
                    json = new ResultMsg("F", "非空参数不可为空");
                    return json;
                }
            }
        }
        json = InfoReleaseCoreCleint.getInstance().updateInfo(params);
        if (null != json && "T".equals(json.getFlag())) {
            this.addLogInfo("edit", "com.apache.pubInfo." + params.get("sortCode"), request,
                    params);
        }
        return json;
    }

    /**
     * 判断信息是否存在
     */
    private ResultMsg checkInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = new ResultMsg("F", "信息不存在");
        Object objs = InfoReleaseCoreCleint.getInstance().selectSingle(params);
        if (null != objs) {
            return new ResultMsg("T", "信息已存在");
        } else {
            return json;
        }
    }

    /**
     * description:  单表删除
     */
    private ResultMsg delInfo(HttpServletRequest request, Map<String, String> params) {
        ResultMsg json = null;
        PubMetadata pm = InfoReleaseCoreCleint.getInstance()
                .getMetadataPrimarykey(params.get("sortCode"), params.get("sysName"));
        if (null != pm) {
            if ("1".equals(pm.getDataRestrict())) {//处理主键
                if (StrUtil.isNull(params.get(pm.getDataAttr()))) {
                    json = new ResultMsg("F", "非空参数不可为空");
                    return json;
                }
            }
        }
        json = InfoReleaseCoreCleint.getInstance().deleteInfo(params);
        if (null != json && "T".equals(json.getFlag())) {
            this.addLogInfo("del", "com.apache.pubInfo." + params.get("sortCode"), request, params);
        }
        return json;
    }

    /**
     * description:  添加审记信息
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void addLogInfo(String logType, String className, HttpServletRequest request, Map map) {
        LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        if (null != loginUser) {
            Map<String, Object> logMap = new HashMap<String, Object>();
            logMap.put("logType", logType);
            logMap.put("logClassName", className);
            logMap.put("logIp", RequestTools.getIp(request));
            logMap.put("log_userEname", loginUser.getUserEname());
            logMap.putAll(map);
            LogClient.getInstance().execute(logMap);//添加日志
        }
    }
}
